package com.app.system.config.task;

import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.Resource;
import java.util.Map;

/**
 * Created by wcf-pc on 2019/1/27.
 */
@Configuration
@SuppressWarnings("all")
public class CompleteScheduleConfig implements SchedulingConfigurer {

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Resource
    private DataDictService dataDictService;

    /**
     * 随着程序而启动，只执行一次
     *
     * @param scheduledTaskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        if (MySqlBackRunnable.future != null) {
            MySqlBackRunnable.future.cancel(true);
        }

        Map<String, DataDict> resultMap = dataDictService.getMapByParentNameForName("系统配置");
        DataDict dataDict = resultMap.get("cronTrigger");
        String cron = "";
        if (dataDict != null) {
            cron = dataDict.getValue();
        }
        if (cron != null && !cron.isEmpty()) {
            MySqlBackRunnable.future = threadPoolTaskScheduler().schedule(new MySqlBackRunnable(), new CronTrigger(cron));
        }
    }
}
